package com.springark.ms.sampleorders.config;

import com.springark.ms.commons.MsApiResult;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.validation.ConstraintViolationException;

/**
 * @author hankchan
 * @since 2019/5/5
 */
@RestControllerAdvice
public class RestControllerExceptionAdvice implements WebMvcConfigurer, ErrorController {

    private static final String ERROR_PATH = "/error";

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false);
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }

    @RequestMapping(value = ERROR_PATH, produces = "application/json;charset=UTF-8")
    public MsApiResult error() {
        return MsApiResult.newInstance().error(-1L, "error", "");
    }

    /**
     * RequestParam的参数校验异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public MsApiResult constraintViolationException(ConstraintViolationException e) {
        return MsApiResult.newInstance().error(-1L,
                e.getConstraintViolations().stream().findFirst().get().getMessageTemplate(), "");
    }

    /**
     * RequestBody的参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public MsApiResult methodArgumentNotValidException(MethodArgumentNotValidException e) {
        return MsApiResult.newInstance().error(-1L,
                e.getBindingResult().getAllErrors().get(0).getDefaultMessage(), "");
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public MsApiResult missingServletRequestParameterException(MissingServletRequestParameterException e) {
        return MsApiResult.newInstance().error(-1L,
                "缺失请求参数:" + e.getParameterName(), "");
    }

    /**
     * 处理意料之外的异常
     * @return JSON格式响应结果
     */
    @ExceptionHandler(Exception.class)
    public MsApiResult unexpectedHandler(Exception e) {
        // 返回提示，服务器内部错误90500
        return MsApiResult.newInstance().error(-1L, e.getMessage(), "");
    }

}
